package baseFx.common.encryption;

import baseFx.common.utils.ByteUtils;
import baseFx.common.utils.ExceptionUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class Encrypt {
    public static String md5(byte[] input) {
        return md5(input, false);
    }

    public static String md5(byte[] input, boolean len16) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] data = md5.digest(input);
            StringBuilder hex = new StringBuilder();
            for (int i = 0; i < data.length; i++) {
                int val = ((int) data[i]) & 0xff;
                if (val < 16) {
                    hex.append("0");
                }
                hex.append(Integer.toHexString(val));
            }
            if (len16) {
                return hex.substring(8, 24);
            }
            return hex.toString();
        } catch (Exception e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }

    public static String md5(String str, String encoding, boolean len16) {
        try {
            encoding = encoding == null ? "UTF-8" : encoding;
            return md5(str.getBytes(encoding), len16);
        } catch (UnsupportedEncodingException e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }

    public static String md5(String str) {
        return md5(str, null);
    }

    public static String md5(String str, String encoding) {
        return md5(str, encoding, false);
    }

    public static String md5(String str, boolean len16) {
        return md5(str, null, len16);
    }

    public static String aes(String value, String key, String padding) {
        try {
            Base64.Encoder encoder = Base64.getEncoder();
            Cipher cipher = Cipher.getInstance(padding);
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec spec = new SecretKeySpec(raw, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, spec);
            byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
            return encoder.encodeToString(encrypted);
        } catch (Exception e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }

    public static String aes(String value, String key) {
        return aes(value, key, "AES/ECB/PKCS5Padding");
    }

    public static String rsaByPublicKey(String input, String pubKey) {
        try {
            Base64.Encoder encoder = Base64.getEncoder();
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] data = input.getBytes(StandardCharsets.UTF_8);
            byte[] keyBytes = decoder.decode(pubKey);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(RSAUtils.ALGORITHM);
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            Cipher cipher = Cipher.getInstance(RSAUtils.ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > RSAUtils.MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, RSAUtils.MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * RSAUtils.MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encoder.encodeToString(encryptedData);
        } catch (Exception e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }

    public static String rsaByPrivateKey(String input, String priKey) {
        try {
            Base64.Encoder encoder = Base64.getEncoder();
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] data = input.getBytes(StandardCharsets.UTF_8);
            byte[] keyBytes = decoder.decode(priKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(RSAUtils.ALGORITHM);
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > RSAUtils.MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, RSAUtils.MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * RSAUtils.MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encoder.encodeToString(encryptedData);
        } catch (Exception e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }

    public static String des(String input, String key, String padding) {
        try {
            DESKeySpec ks = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            SecretKey sk = skf.generateSecret(ks);
            Cipher cip = Cipher.getInstance(padding);
            byte[] iv = key.getBytes(StandardCharsets.UTF_8);
            IvParameterSpec iv2 = new IvParameterSpec(iv);
            cip.init(Cipher.ENCRYPT_MODE, sk, iv2);
            byte[] data = cip.doFinal(input.getBytes(StandardCharsets.UTF_8));
            return ByteUtils.encode(data);
        } catch (Exception e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }

    public static String des(String input, String key) {
        return des(input, key, "DES/CBC/PKCS5Padding");
    }

    public static String sha256(String input) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(input.getBytes(StandardCharsets.UTF_8));
            return ByteUtils.byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("加密失败", e);
        }
    }
}
